package org.example.kidscode.controller;

import org.example.kidscode.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class LoginController {
    private final UserService userService;
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        Map<String, Object> result = new HashMap<>();
        if (userService.checkPassword(username, password)) {
            result.put("code", 200);
            result.put("msg", "登录成功");
            // 可以生成token等
        } else {
            result.put("code", 401);
            result.put("msg", "用户名或密码错误");
        }
        return result;
    }
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> registerForm) {
        String username = registerForm.get("username");
        String password = registerForm.get("password");
        Map<String, Object> result = new HashMap<>();
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "用户名和密码不能为空");
            return result;
        }
        boolean success = userService.register(username, password);
        if (success) {
            result.put("code", 200);
            result.put("msg", "注册成功");
        } else {
            result.put("code", 409);
            result.put("msg", "用户名已存在");
        }
        return result;
    }
}